<template>
    <div class="container">
        <!-- 搜索栏 -->
        <div class="search-section">
            <el-form :model="queryData" class="search-form">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">预约日期</label>
                        <el-date-picker v-model="queryData.date" :clearable="false" @change="handleDateChange" type="date" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd" :picker-options="pickerOptions" class="date-picker"
                            prefix-icon="el-icon-date" />
                    </div>

                    <div class="form-group">
                        <label class="form-label">课程节次</label>
                        <el-select v-model="joint" class="session-select" placeholder="全部节次" @change="changeSelect">
                            <el-option v-for="item in jointNum" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </div>

                    <el-button type="primary" class="search-btn" @click="handleQuery">
                        <i class="el-icon-search"></i>
                        立即搜索
                    </el-button>
                </div>
            </el-form>
        </div>

        <!-- 教室列表 -->
        <div v-if="formData.length">
            <div class="card-list">
                <div v-for="(item, index) in formDatas" :key="index" class="card-item"
                    :class="{ 'reserved-card': item.statusName }">
                    <div class="card-header">
                        <div class="title-wrap">
                            <h3 class="card-title">{{ item.classroom }}</h3>
                            <div class="status-tag" :class="statusClass(item)">
                                {{ item.statusName || '可预约' }}
                            </div>
                        </div>
                        <el-button :type="buttonType(item)" class="action-btn" @click="handleAction(item)"
                            :disabled="item.statusName === '通过'">
                            {{ actionText(item) }}
                        </el-button>
                    </div>

                    <div class="card-body">
                        <div class="info-item">
                            <span class="info-label">课程节次：</span>
                            <span class="info-content">{{ formatSession(item.session) }}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">预约日期：</span>
                            <span class="info-content">{{ queryData.date }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 分页 -->
            <pagination v-show="queryData.total > 0" :total="queryData.total" :page.sync="queryData.pageNum"
                :limit.sync="queryData.pageSize" class="list-pagination" />
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
            <!-- <img src="@/assets/empty-class.png" class="empty-img"> -->
            <p class="empty-text">当前没有可用的教室</p>
        </div>

        <!-- 预约弹窗 -->
        <el-dialog title="教室预约申请" :visible.sync="dialogVisible" class="reservation-dialog" width="600px">
            <el-form :model="addInfo" :rules="rules" ref="reservationForm" label-width="100px">
                <el-form-item label="预约日期：">
                    <el-date-picker v-model="addInfo.date" type="date" disabled class="dialog-field" />
                </el-form-item>

                <el-form-item label="教室地点：">
                    <el-input v-model="addInfo.classroom" disabled class="dialog-field" />
                </el-form-item>

                <el-form-item label="课程节次：">
                    <el-input v-model="addInfo.sessionName" disabled class="dialog-field" />
                </el-form-item>

                <el-form-item label="预约人数：" prop="peopleNum">
                    <el-input-number v-model="addInfo.peopleNum" :min="1" controls-position="right"
                        class="number-input" />
                </el-form-item>

                <el-form-item label="预约单位：" prop="applicantUnit">
                    <el-input v-model="addInfo.applicantUnit" placeholder="请输入预约单位" class="dialog-field" />
                </el-form-item>
                </el-form-item>

                <el-form-item label="预约人：" prop="applicant">
                    <el-input v-model="addInfo.applicant" placeholder="请输入预约人" class="dialog-field" />
                </el-form-item>

                <el-form-item label="联系方式：" prop="contactInformation">
                    <el-input v-model="addInfo.contactInformation" placeholder="请输入手机号" class="dialog-field" />
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" class="dialog-btn">取消</el-button>
                <el-button type="primary" @click="submitReservation" class="dialog-btn">立即预约</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getBookCourseList, getEmptyCourseList, addCourse, deleteCourseById } from "@/api/classroomReservation.js"
import Pagination from "@/components/Pagination/index.vue"

export default {
    components: {
        Pagination
    },
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    const now = new Date()
                    const currentDay = now.getDay()
                    if (currentDay === 6) now.setDate(now.getDate() + 2)
                    else if (currentDay === 0) now.setDate(now.getDate() + 1)
                    return time < now.setHours(0, 0, 0, 0)
                }
            },
            queryData: {
                date: "",
                classStart: "",
                classEnd: "",
                total: 0,
                pageNum: 1,
                pageSize: 10
            },
            joint: "",
            jointNum: [
                { label: "全部节次", value: "" },
                { label: "1-2节", value: "1-2" },
                { label: "3-4节", value: "3-4" },
                { label: "5-6节", value: "5-6" },
                { label: "7-8节", value: "7-8" },
                { label: "9-10节", value: "9-10" },
                { label: "11-12节", value: "11-12" }
            ],
            formData: [],
            dialogVisible: false,
            addInfo: {
                applicant: "",
                applicantUnit: "",
                classroom: "",
                contactInformation: "",
                date: "",
                peopleNum: 1,
                session: "",
                sessionName: ""
            },
            rules: {
                peopleNum: [
                    { type: "number", min: 1, message: "人数不能小于1", trigger: "blur" }
                ],
                applicantUnit: [
                    { required: true, message: "请输入预约单位", trigger: "blur" }
                ],
                applicant: [
                    { required: true, message: "请输入预约人姓名", trigger: "blur" }
                ],
                contactInformation: [
                    { required: true, message: "请输入联系方式", trigger: "blur" },
                    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
                ]
            }
        }
    },
    computed: {
        formDatas() {
            return this.formData.slice(
                (this.queryData.pageNum - 1) * this.queryData.pageSize,
                this.queryData.pageNum * this.queryData.pageSize
            )
        }
    },
    async created() {
        this.queryData.date = this.getDefaultDate()
        await this.initData()
    },
    methods: {
        // 初始化数据
        async initData() {
            await this.getBookedList()
            this.getAvailableList()
        },

        // 获取默认日期
        getDefaultDate() {
            const now = new Date();
            const currentDay = now.getDay(); // 0（周日）到 6（周六）

            // 如果是周六或周日，计算下周一的日期
            if (currentDay === 6) {
                now.setDate(now.getDate() + 2);
            } else if (currentDay === 0) {
                now.setDate(now.getDate() + 1);
            }

            // 格式化日期为 YYYY-MM-DD，确保月和日是两位数
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
            const day = String(now.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        },

        // 获取已预约列表
        async getBookedList() {
            try {
                const res = await getBookCourseList(1, 9999)
                if (res.code === 20000) {
                    this.formData = res.data.list.records.filter(e => e.statusName !== "未通过")
                }
            } catch (error) {
                console.error("获取预约数据失败:", error)
            }
        },

        // 获取可预约列表
        async getAvailableList() {
            try {
                const res = await getEmptyCourseList(this.queryData)
                if (res.code === 20000) {
                    this.formData = [...this.formData, ...res.data.availableCourses]
                    this.queryData.total = this.formData.length
                }
            } catch (error) {
                console.error("获取空闲教室失败:", error)
            }
        },

        // 处理搜索
        async handleQuery() {
            this.queryData.pageNum = 1
            await this.initData()
        },

        // 处理节次选择
        changeSelect(val) {
            if (val) {
                const [start, end] = val.split("-")
                this.queryData.classStart = start
                this.queryData.classEnd = end
            } else {
                this.queryData.classStart = ""
                this.queryData.classEnd = ""
            }
        },

        // 处理操作按钮
        handleAction(item) {
            if (!item.statusName) {
                this.showReservationDialog(item)
            } else if (item.statusName !== "通过") {
                this.cancelReservation(item)
            }
        },

        // 显示预约对话框
        showReservationDialog(item) {
            this.dialogVisible = true
            this.addInfo = {
                ...this.addInfo,
                classroom: item.classroom,
                date: this.queryData.date,
                session: item.session,
                sessionName: item.session.substring(2, item.session.length - 1)
            }
        },

        // 提交预约
        submitReservation() {
            this.$refs.reservationForm.validate(valid => {
                if (valid) {
                    addCourse(this.addInfo)
                        .then(res => {
                            if (res.code === 20000) {
                                this.$message.success("预约成功")
                                this.dialogVisible = false
                                this.initData()
                            }
                        })
                        .catch(err => {
                            this.$message.error(err.message || "预约失败")
                        })
                }
            })
        },

        // 取消预约
        async cancelReservation(item) {
            try {
                await this.$confirm("确定要取消该预约吗？", "提示", { type: "warning" })
                const res = await deleteCourseById(item.id)
                if (res.code === 20000) {
                    this.$message.success("取消成功")
                    this.initData()
                }
            } catch (error) {
                console.log("取消操作已中断")
            }
        },

        // 状态样式
        statusClass(item) {
            return {
                'status-available': !item.statusName,
                'status-approved': item.statusName === '通过',
                'status-other': item.statusName && item.statusName !== '通过'
            }
        },

        handleDateChange(value) {
            if (!value) this.queryData.date = this.getDefaultDate()
        },

        // 按钮类型
        buttonType(item) {
            return !item.statusName ? 'primary' : item.statusName === '通过' ? 'success' : 'danger'
        },

        // 按钮文字
        actionText(item) {
            return !item.statusName ? '立即预约' : item.statusName === '通过' ? '✓ 预约成功' : '取消预约'
        },

        // 格式化节次显示
        formatSession(session) {
            return session?.replace(/[一二三四五六七日\[\]]/g, '').replace(',', ' - ') || ''
        }
    }
}
</script>

<style scoped>
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

/* 搜索区域 */
.search-section {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.form-row {
    display: flex;
    gap: 16px;
    flex-wrap: wrap;
    align-items: center;
}

.form-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-label {
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
}

.date-picker,
.session-select {
    width: 240px;
}

.search-btn {
    height: 40px;
    padding: 0 24px;
    margin-left: auto;
}

/* 教室卡片 */
.card-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
}

.card-item {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s;
}

.card-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.reserved-card {
    background: #f8f9fa;
    opacity: 0.8;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
}

.title-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
}

.card-title {
    font-size: 16px;
    color: #303133;
    margin: 0;
}

.status-tag {
    font-size: 12px;
    padding: 4px 10px;
    border-radius: 12px;
}

/* 状态颜色 */
.status-available {
    background: #e8f4ff;
    color: #409eff;
}

.status-approved {
    background: #e1f3d8;
    color: #67c23a;
}

.status-other {
    background: #f0f0f0;
    color: #909399;
}

.action-btn {
    padding: 8px 16px;
    border-radius: 16px;
    transition: all 0.2s;
}

/* 卡片内容 */
.card-body {
    padding-top: 12px;
}

.info-item {
    display: flex;
    font-size: 14px;
    margin-bottom: 12px;
}

.info-label {
    color: #909399;
    min-width: 80px;
}

.info-content {
    color: #606266;
    flex: 1;
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 0;
}

.empty-img {
    width: 200px;
    opacity: 0.6;
    margin-bottom: 20px;
}

.empty-text {
    color: #909399;
    font-size: 14px;
}

/* 弹窗样式 */
.reservation-dialog .el-dialog__body {
    padding: 20px 30px;
}

.dialog-field {
    width: 100%;
}

.number-input {
    width: 200px;
}

.dialog-footer {
    padding: 16px 30px;
    border-top: 1px solid #eee;
}

.dialog-btn {
    padding: 10px 24px;
    border-radius: 6px;
}

.list-pagination {
    margin-top: 20px;
    text-align: center;
}
.el-button--success.is-disabled {
    background-color: #67c23a;
    border-color: #67c23a;
}

/* 响应式 */
@media (max-width: 768px) {
    .container {
        padding: 12px;
    }

    .search-section {
        padding: 16px;
    }

    .form-row {
        flex-direction: column;
        align-items: stretch;
    }

    .form-group {
        flex-direction: column;
        align-items: flex-start;
    }

    .date-picker,
    .session-select {
        width: 100%;
    }

    .search-btn {
        width: 100%;
        margin-left: 0;
    }

    .card-list {
        grid-template-columns: 1fr;
    }

    .reservation-dialog .el-dialog {
        width: 90% !important;
    }
}
</style>